import requests
import sys

from plugins.plugin import Plugin
from src.history import History
from src.config import Config

sys.path.append("..")
from src.video import Video
from src.playlist import Playlist

class SovetRomantica(Plugin):

    def __init__(self, history: History=History(), config: Config=Config()):
        super().__init__(history, config)

        self.history = history
        self.config = config

        self.name = "[+] SovetRomantica: Search"
        self.category = "SovetRomantica"

        self.query_description = """"""
        self.history = history

        self.params = {
            'query' : True
        }

        self.flag = "-sr"
        self.full_flag = "--sovetromantica"
        self.flag_help = "search sovetromantica titles"
        self.flag_action = ""

        self.save_config()

        self.api_instance = self.config.get_option(self.category, 'api-instance')

    def get_episodes(self, anime_id):
        resp = requests.get(
            f"{self.api_instance}/anime/{anime_id}/episodes" 
        )

        if resp.status_code != 200: return list()
        episodes = resp.json()

        return episodes

    def get_search(self, query: str=""):
        resp = requests.get(f"{self.api_instance}/animesearch", 
            {
                "anime_name" : query
            }
        )

        if resp.status_code != 200: return list()
        anime_list = resp.json()

        items = []
        for it in anime_list:
            if type(it) != dict: continue
            title = f"{it['anime_name']} ({it['anime_name_russian']})"
            anime_id = it['anime_id']

            episodes = list()
            episodes_js = self.get_episodes(anime_id)
            for episode in episodes_js:
                if type(episode) != dict or episode['episode_type'] > 0: continue

                ititle = f"Episode {episode['episode_count']}"
                video = Video(
                    title=ititle,
                    #playlist_title=title,
                    url=episode['embed']
                )

                video.isWatched = video.in_history(self.history)

                item = video.to_json()

                episodes.append(item)
            
            episodes.sort(key=lambda v: int(v['title'][8:]))
            playlist = Playlist(title, episodes)

            items.append(playlist.to_json())

        return items

    def get_items(self, params):
        query = ""
        if 'query' in params:
            query = params['query']
        return self.get_search(query=query)

    def save_config(self):
        self.config.set_option(self.category, 'api-instance', 'https://service.sovetromantica.com/v1')



